package cz.kfad.ofrss.common;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
import cz.kfad.ofrss.R;
import cz.kfad.ofrss.backend.BackendService;
import cz.kfad.ofrss.rss.ContentFetcherImp;
import cz.kfad.ofrss.synchronization.SyncScheduler;

public class AsynRefresh extends AsyncTask<Void, Void, Void> {

	public static final String TAG = SyncScheduler.class.getSimpleName();
    private DoneCallback done;
    private Activity context;
    private volatile boolean started = false;
    private volatile boolean ended = false;

    public AsynRefresh() {
        super();
    }

    public AsynRefresh(Activity context, DoneCallback done) {
        super();
        this.done = done;
        this.context = context;
    }

    public Activity getContext() {
        return context;
    }

    public void setContext(Activity context) {
        this.context = context;
    }

    public boolean isStarted() {
        return started;
    }

    public boolean isEnded() {
        return ended;
    }

    public void setDone(DoneCallback done) {
        this.done = done;
    }

    @Override
    protected void onPreExecute() {
        if (started) {
            throw new RuntimeException("asyn task has been already executed");
        }
        started = true;
        Toast.makeText(context, context.getString(R.string.fetchStarted), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected Void doInBackground(Void... params) {
		if (!NetworkHelper.isNetworkConnected(context)) {
			return null;
		}
        BackendService.createBackend(context).refreshFeeds();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        ended = true;
		if (context == null) {
			return;
		}
		Toast.makeText(context, context.getString(R.string.fetchEnded), Toast.LENGTH_SHORT).show();
		if (done != null) {
			done.done();
		}
		if (!NetworkHelper.isNetworkConnected(context)) {
			return;
		}
		AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				new ContentFetcherImp(context).fetchContentForAll();
				return null;
			}

		};
		asyncTask.execute();
        }
}
